package com.example.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.example.entity.Package;
import com.example.exception.CustomerException;
import com.example.mapper.PackageMapper;
import com.example.mapper.PickupCodeMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PackageService {

    @Resource
    PackageMapper packageMapper;

    @Resource
    private GeneratorService generatorService;

    @Resource
    private PickupCodeMapper pickupCodeMapper;

    public void add(Package pack) {

        // 根据新的包裹单号查询数据库 判断包裹单号是否已存在
        Package dbPackage = packageMapper.selectByTrackingNumber(pack.getTrackingNumber());
        if (dbPackage != null) {
            throw new CustomerException("快递单号已存在");
        }

        // 设置默认的包裹名称
        if (StrUtil.isBlank(pack.getPackageName())){
            pack.setPackageName("未命名");
        }

        // 生成二维码并保存路径
        try {
            String qrCodePath = generatorService.generateQRCode(pack.getTrackingNumber());
            pack.setQrCode(qrCodePath);
        } catch (Exception e) {
            throw new CustomerException("二维码生成失败：" + e.getMessage());
        }

        // 插入数据库
        packageMapper.insert(pack);

    }

    public void update(Package pack) {
        // 仅在qrCode为空时生成新二维码
        if (StrUtil.isBlank(pack.getQrCode()) && StrUtil.isNotBlank(pack.getTrackingNumber())) {
            try {
                String qrCodePath = generatorService.generateQRCode(pack.getTrackingNumber());
                pack.setQrCode(qrCodePath);
            } catch (Exception e) {
                throw new CustomerException("二维码生成失败：" + e.getMessage());
            }
        }

        packageMapper.updateById(pack);

        // 状态检查
        boolean isPendingReceipt = "待签收".equals(pack.getState());

        if (isPendingReceipt) {
            // 生成取件码并设置到对象
            String pickupCode = generatorService.generatePickupCode(pack.getTrackingNumber());
            pack.setPickupCode(pickupCode);

            // 设置入库时间为当前时间
            pack.setInboundTime(DateUtil.now());
        }

        // 统一执行数据库更新
        packageMapper.updateById(pack);

        // 如果状态为已签收，无论取件码是否为空，都清空 pickup_code 表中的 trackingNumber
        if ("已签收".equals(pack.getState())) {
            // 1. 清空 package 表的取件码
            packageMapper.clearPickupCode(pack.getTrackingNumber());
            // 2. 清空 pickup_code 表的 trackingNumber
            generatorService.recyclePickupCode(pack.getTrackingNumber());
        }
    }

    public void updateBatchStatus(List<Integer> ids, String state) {
        // 仅当状态为"待签收"时设置入库时间
        LocalDateTime inboundTime = "待签收".equals(state) ? DateUtil.date().toLocalDateTime() : null;

        // 清空取件码的条件：当状态变为"已签收"
        if ("已签收".equals(state)) {
            // 清空package表取件码
            packageMapper.clearPickupCodes(ids);
            // 获取这些包裹的 trackingNumber 列表
            List<String> trackingNumbers = packageMapper.selectTrackingNumbersByIds(ids);
            if (!trackingNumbers.isEmpty()) {
                // 3. 清空 pickup_code 表中对应的 trackingNumber
                pickupCodeMapper.clearTrackingNumbers(trackingNumbers);
            }
        }
        packageMapper.updateBatchStatus(ids, state, inboundTime);
    }

    public void deleteById(Integer id) {
        packageMapper.deleteById(id);
    }

    public void deleteBatch(List<Package> list) {
        for (Package aPackage : list) {
            this.deleteById(aPackage.getId());
        }
    }

    public List<Package> selectPackage(Package pack) {
        return packageMapper.selectPackage(pack);
    }

    public PageInfo<Package> selectPage(Integer pageNum, Integer pageSize, Package queryPackage) {
        // 开启分页功能
        PageHelper.startPage(pageNum,pageSize);
        List<Package> packageList = packageMapper.selectPackage(queryPackage);
        return PageInfo.of(packageList);
    }

    public int getPackageTotal() {
        return packageMapper.selectPackageTotal();
    }

    public int getPendingPackageTotal() {
        return packageMapper.selectPendingPackageTotal();
    }


}
